package com.fire.chat.controller;


import com.fire.chat.annotaiton.AdminLogin;
import com.fire.chat.annotation.BusinessLog;
import com.fire.chat.annotation.CheckPermissions;
import com.fire.chat.cache.AuthorityCacheStrategy;
import com.fire.chat.constant.CacheConstant;
import com.fire.chat.entity.bo.SysMenuBO;
import com.fire.chat.entity.bo.SysRoleBO;
import com.fire.chat.entity.bo.SysUserRoleBO;
import com.fire.chat.entity.po.SysMenu;
import com.fire.chat.entity.response.BaseResponse;
import com.fire.chat.entity.vo.SysMenuVO;
import com.fire.chat.entity.vo.SysRoleVO;
import com.fire.chat.enums.BusinessDataModel;
import com.fire.chat.enums.LogActionType;
import com.fire.chat.exception.BusinessException;
import com.fire.chat.service.SysMenuService;
import com.fire.chat.service.SysRoleService;
import com.fire.chat.service.SysUserRoleRefService;
import com.fire.chat.utils.common.AdminLoginUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @program: hxzq
 * @description: 菜单资源控制层
 * @author: xjr
 * @create: 2020-11-05 10:47
 **/
@RestController
@Api(tags = "后台管理-权限管理")
@RequestMapping("/auth")
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class SysMenuController {


    private final SysMenuService menuService;


    private final SysRoleService sysRoleService;


    private final AuthorityCacheStrategy authorityCacheStrategy;


    private final SysUserRoleRefService userRoleRefService;



    @GetMapping("/menu/tree")
    @ApiOperation("权限管理-菜单列表")
    @CheckPermissions("auth:menu:tree")
    public BaseResponse<List<SysMenuVO>> queryMenuTree(){
        return BaseResponse.success(menuService.queryMenuTree());
    }


    @PutMapping("/menu/refresh")
    @ApiOperation(value = "权限管理-刷新用户权限",tags = "对请求调用者")
    @CheckPermissions("auth")
    @AdminLogin
    public BaseResponse<List<SysMenuVO>> refresh(){
        String userId= AdminLoginUtil.get().getUserId().toString();
        if (authorityCacheStrategy!=null){
            authorityCacheStrategy.remove(String.format("%s:%s", CacheConstant.USER_KEY_PREFIX, userId));
        }
        return BaseResponse.success(menuService.queryMenuByUserId(Long.valueOf(userId)));
    }


    @PutMapping("/menu/refresh/{uid}")
    @ApiOperation(value = "权限管理-刷新用户权限",tags = "根据传入的用户ID")
    @CheckPermissions("auth")
    @AdminLogin
    public BaseResponse<List<SysMenuVO>> refreshOne(@PathVariable("uid") String uid){
        if (authorityCacheStrategy!=null){
            authorityCacheStrategy.remove(String.format("%s:%s",CacheConstant.USER_KEY_PREFIX, uid));
        }
        return BaseResponse.success(menuService.queryMenuByUserId(Long.valueOf(uid)));
    }


    @PostMapping("/menu")
    @ApiOperation("权限管理-菜单新增")
    @CheckPermissions(("auth:menu:add"))
    @AdminLogin
    public BaseResponse add(@RequestBody @Valid SysMenuBO menuBO){
        menuService.addMenu(menuBO);
        return BaseResponse.success("添加成功");
    }

    @DeleteMapping("/menu/{id}")
    @ApiOperation(value = "权限管理-菜单删除",tags = "逻辑删除")
    @CheckPermissions(("auth:menu:delete"))
    @BusinessLog(type =LogActionType.UPDATE,table = BusinessDataModel.ROLE,value = "删除id为#{#id}的菜单")
    public BaseResponse deleteMenu(@PathVariable("id") @ApiParam("菜单id") String id){
        menuService.deleteById(id);
        return BaseResponse.success("删除成功");
    }

    @PutMapping("/menu")
    @ApiOperation("权限管理-菜单修改")
    @CheckPermissions(("auth:menu:update"))
    @AdminLogin
    @BusinessLog(type =LogActionType.UPDATE,table = BusinessDataModel.MENU,value = "更新id为#{#id}的菜单")
    public BaseResponse updateMenu(@RequestBody @Valid SysMenuBO menuBO){
        if (menuBO.getId()==null){
            throw new BusinessException("菜单ID不得为空");
        }
        SysMenu sysMenu=SysMenu.builder().iconUrl(menuBO.getIcon()).level(menuBO.getLevel()).menuCode(menuBO.getMenuCode())
                .name(menuBO.getName()).nodeType(menuBO.getNodeType()).parentId(menuBO.getPid()).isDelete(menuBO.getIsDelete()).build();
        sysMenu.setId(menuBO.getId());
        menuService.updateById(sysMenu);
        if (authorityCacheStrategy!=null){
            authorityCacheStrategy.remove(CacheConstant.MENU_KEY);
        }
        return BaseResponse.success("更新成功");
    }



    @PostMapping("/role")
    @ApiOperation("权限管理-角色新增")
    @CheckPermissions(("auth:role:add"))
    @AdminLogin
    @BusinessLog(type = LogActionType.INSERT,table = BusinessDataModel.ROLE,value = "新增角色编码为#{#role.code}的角色")
    public BaseResponse addRole(@RequestBody @Valid SysRoleBO role){
        sysRoleService.addRole(role);
        return BaseResponse.success("添加成功");
    }

    @GetMapping("/role/list")
    @ApiOperation("权限管理-角色列表")
    @CheckPermissions(("auth:role:browser"))
    @BusinessLog(type = LogActionType.SELECT,table = BusinessDataModel.ROLE)
    @AdminLogin
    public BaseResponse<List<SysRoleVO>> roleList(){
        return BaseResponse.success(sysRoleService.roleList());
    }


    @PutMapping("/role")
    @ApiOperation("权限管理-角色更新")
    @CheckPermissions(("auth:role:update"))
    @AdminLogin
    @BusinessLog(type =LogActionType.UPDATE,table = BusinessDataModel.ROLE,value = "更新id为#{#id}的角色")
    public BaseResponse updateRole(@RequestBody @Valid SysRoleBO role){
        sysRoleService.updateRole(role);
        return BaseResponse.success("更新角色成功");
    }


    @DeleteMapping("/role/{id}")
    @ApiOperation("权限管理-角色删除")
    @CheckPermissions(("auth:role:delete"))
    @BusinessLog(type = LogActionType.DELETE,table = BusinessDataModel.ROLE,value = "删除角色id为#{#id}的角色")
    @AdminLogin
    public BaseResponse deleteRole(@PathVariable("id") String id){
        sysRoleService.deleteRole(id);
        return BaseResponse.success("删除成功");
    }


    @PutMapping("/deliverRights")
    @ApiOperation("权限管理-角色分配")
    @AdminLogin
    public BaseResponse deliverRights(@RequestBody @Valid SysUserRoleBO userRoleBO){
        userRoleRefService.deliverRights(userRoleBO);
        return BaseResponse.success("分配成功");
    }








}
